<template>
  <div class="permissiom-wrapper">
    <!-- 搜索框 -->
    <Form :model="formSearch" label-position="right" label-colon :label-width="80">
      <Row :gutter="10">
        <Col :xs="24" :sm="24" :md="12" :lg="6">
          <FormItem label="权限">
            <Input v-model="formSearch.name" placeholder="请输入权限名称"/>
          </FormItem>
        </Col>
        <Col :xs="24" :sm="24" :md="12" :lg="6">
          <FormItem label="接口路径">
            <Input v-model="formSearch.path" placeholder="请输入接口路径"/>
          </FormItem>
        </Col>
        <Col :xs="24" :sm="24" :md="12" :lg="6">
          <FormItem label="系统码">
            <Input v-model="formSearch.sysCode" placeholder="请输入系统码"/>
          </FormItem>
        </Col>
        <Col :xs="24" :sm="24" :md="12" :lg="6">
          <FormItem>
            <Button type="primary" @click="querySearch" shape="circle" icon="ios-search">查询</Button>
          </FormItem>
        </Col>
      </Row>
    </Form>

    <!-- 工具栏 -->
    <div class="tool-box">
      <Button type="primary" icon="md-add" ghost @click="addModel = true">添加权限</Button>
      <Button type="error" icon="md-trash" ghost style="margin-left:10px;">批量删除</Button>
    </div>

    <!-- 表格数据 -->
    <Table :loading="loading" border ref="selection" :columns="columns" :data="tableData"></Table>

    <!-- 分页按钮 -->
    <div class="page-wrapper">
      <Page :total="total" @on-change="handlePage" show-elevator show-total/>
    </div>

    <!-- 添加权限 -->
    <div>
      <Modal
        v-model="addModel"
        title="添加权限"
        @on-ok="handelAdd"
        @on-cancel="cancelAdd"
      >
        <Form ref="formInlineAdd" label-colon :label-width="85" :model="formAdd" :rules="ruleInlineAdd">
          <FormItem label="权限" prop="name">
            <Input v-model="formAdd.name" placeholder="请输入权限，必填"/>
          </FormItem>
          <FormItem label="接口路径" prop="path">
            <Input v-model="formAdd.path" placeholder="请输入接口路径，必填"/>
          </FormItem>
          <FormItem label="系统码">
            <Input v-model="formAdd.sysCode" placeholder="请输入系统码"/>
          </FormItem>
          <FormItem label="权限说明">
            <Input v-model="formAdd.note" placeholder="请输入权限说明"/>
          </FormItem>
        </Form>
      </Modal>
    </div>

    <!-- 修改权限 -->
    <div>
      <Modal
        v-model="editModel"
        title="修改权限"
        @on-ok="handelEdit"
        @on-cancel="cancelEdit"
      >
        <Form ref="formInlineEdit" label-colon :label-width="85" :model="formEdit" :rules="ruleInlineEdit">
          <FormItem label="权限" prop="name">
            <Input v-model="formEdit.name" placeholder="请输入权限，必填"/>
          </FormItem>
          <FormItem label="接口路径" prop="path">
            <Input v-model="formEdit.path" placeholder="请输入接口路径，必填"/>
          </FormItem>
          <FormItem label="系统码">
            <Input v-model="formEdit.sysCode" placeholder="请输入系统码"/>
          </FormItem>
          <FormItem label="权限说明">
            <Input v-model="formEdit.note" placeholder="请输入权限说明"/>
          </FormItem>
        </Form>
      </Modal>
    </div>

  </div>
</template>

<script>
import {queryPermission,checkName,checkPath,addPermission,updatePermission,deletePermission} from '@/api/permission'

export default {
  name: 'Permission',
  data(){
    /**
     * 校验权限是否已存在
     */
    const validateName = (rule, value, callback) => {
      if(value && value.trim() != ''){
        checkName({id: '', name: value}).then(res => {
          if(res.data.status){
            callback()
          }else{
            callback(new Error(res.data.msg))
          }
        })
      }else{
        callback()
      }
    }

    const validateNameEdit = (rule, value, callback) => {
      if(value && value.trim() != ''){
        checkName({id: this.formEdit.id, name: value}).then(res => {
          if(res.data.status){
            callback()
          }else{
            callback(new Error(res.data.msg))
          }
        })
      }else{
        callback()
      }
    }
    /**
     * 校验接口路径是否存在
     */
    const validatePath = (rule, value, callback) => {
      if(value && value.trim() != ''){
        checkPath({id: '', path: value}).then(res => {
          if(res.data.status){
            callback()
          }else{
            callback(new Error(res.data.msg))
          }
        })
      }else{
        callback()
      }
    }

    const validatePathEdit = (rule, value, callback) => {
      if(value && value.trim() != ''){
        checkPath({id: this.formEdit.id, path: value}).then(res => {
          if(res.data.status){
            callback()
          }else{
            callback(new Error(res.data.msg))
          }
        })
      }else{
        callback()
      }
    }

    return {
      formSearch: {
        name: '',
        path: '',
        sysCode: ''
      },
      tableData: [],
      total: 0,
      loading: false,
      columns: [
        {
          type: 'selection',
          align: 'center',
          width: 60,
          fixed: 'left'
        },
        {
          type: 'index',
          width: 60,
          align: 'center'
        },
        {
          title: '权限',
          key: 'name',
          minWidth: 150
        },
        {
          title: '接口路径',
          key: 'path',
          minWidth: 150
        },
        {
          title: '系统码',
          key: 'sysCode',
          minWidth: 150
        },
        {
          title: '权限说明',
          key: 'note',
          minWidth: 150
        },
        {
          title: '创建时间',
          key: 'createTime',
          minWidth: 170
        },
        {
          title: '更新时间',
          key: 'updateTime',
          minWidth: 170
        },
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: 130,
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'text',
                  size: 'small'
                },
                on: {
                  click: () => {
                    this.editModel = true
                    this.formEdit = {...params.row}
                  }
                }
              }, '修改'),
              h('Button', {
                props: {
                  type: 'text',
                  size: 'small'
                },
                on: {
                  click: () => {
                    this.$Modal.confirm({
                      title: '删除角色',
                      content: '您确认要删除权限：<strong>'+params.row.name+'</strong> 吗?',
                      onOk: () => {
                        let ids = []
                        ids.push(params.row.id)
                        deletePermission(ids).then(res => {
                          if(res.data.status){
                            this.$Message.success('删除成功')
                            this.tableData.forEach((item,index, arr) => {
                              if(item.id === params.row.id){
                                arr.splice(index, 1)
                                this.total = this.total - 1
                              }
                            })
                          }
                        })
                      }
                    })
                  }
                }
              }, '删除')
            ]);
          }
        }
      ],
      addModel: false,
      formAdd: {
        name: '',
        path: '',
        sysCode: '',
        note: ''
      },
      ruleInlineAdd: {
        name: [
          { required: true, message: '权限不能为空'},
          { validator: validateName, trigger: 'blur' }
        ],
        path: [
          { required: true, message: '接口路径不能为空'},
          { validator: validatePath, trigger: 'blur' }
        ]
      },
      editModel: false,
      formEdit: {
        name: '',
        path: '',
        sysCode: '',
        note: ''
      },
      ruleInlineEdit: {
        name: [
          { required: true, message: '权限不能为空'},
          { validator: validateNameEdit, trigger: 'blur' }
        ],
        path: [
          { required: true, message: '接口路径不能为空'},
          { validator: validatePathEdit, trigger: 'blur' }
        ]
      },
    }
  },
  methods:{
    /**
     * 处理搜索
     */
    querySearch(){
      this.loading = true
      queryPermission({
        pageSize: 10,
        pageNum: 1,
        name: this.formSearch.name,
        path: this.formSearch.path,
        sysCode: this.formSearch.sysCode
      }).then(res => {
        this.loading = false
        if(res.data.status){
          this.tableData = res.data.data.list == null ? [] : res.data.data.list
          this.total = res.data.data.total
        }
      }).catch(()=>{
        this.loading = false
      })
    },
    /**
     * 处理分页
     */
    handlePage(pageNum){
      this.loading = true
      queryPermission({
        pageSize: 10,
        pageNum: pageNum,
        name: this.formSearch.name,
        path: this.formSearch.path,
        sysCode: this.formSearch.sysCode
      }).then(res => {
        this.loading = false
        if(res.data.status){
          this.tableData = res.data.data.list == null ? [] : res.data.data.list
          this.total = res.data.data.total
        }
      }).catch(()=>{
        this.loading = false
      })
    },
    /**
     * 处理添加权限
     */
    handelAdd(){
      this.$refs['formInlineAdd'].validate((valid) => {
        if(valid){
          addPermission(this.formAdd).then(res => {
            if(res.data.status){
              this.$Message.success('添加成功')
              this.querySearch()
              this.cancelAdd()
              this.addModel = false
            }
          })
        }
      })
    },
    /**
     * 处理添加界面关闭
     */
    cancelAdd(){
      this.formAdd = {
        name: '',
        path: '',
        sysCode: '',
        note: ''
      }
      this.$refs.formInlineAdd.resetFields()
    },
    /**
     * 处理修改权限保存
     */
    handelEdit(){
      this.$refs['formInlineEdit'].validate((valid) => {
        if(valid){
          updatePermission(this.formEdit).then(res => {
            if(res.data.status){
              this.$Message.success('修改成功')
              this.querySearch()
              this.cancelEdit()
              this.editModel = false
            }
          })
        }
      })
    },
    /**
     * 处理修改权限界面关闭
     */
    cancelEdit(){
      this.formEdit = {
        name: '',
        path: '',
        sysCode: '',
        note: ''
      }
      this.$refs.formInlineEdit.resetFields()
    }
  },
  created(){
    // 初始化表格数据
    this.querySearch()
  }
}
</script>

<style lang="less">
.permissiom-wrapper{
  padding: 10px;
  .tool-box{
    padding: 10px;
    padding-left: 0;
  }
  .page-wrapper{
    padding-top: 10px;
    padding-bottom: 10px;
  }
}
</style>
